"use client"

import { useState, useEffect, useRef } from "react"
import { View, Text, TouchableOpacity, Alert, Animated, StyleSheet, Platform } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { ArrowLeft, Settings, BookOpen, ArrowDownUp, Trash2, Plus, X } from "lucide-react-native"
import { useRouter } from "expo-router"
import { theme } from "../constants/theme"
import { SortMenu } from "../components/learning/SortMenu"
import { SettingsMenu } from "../components/learning/SettingsMenu"
import { PracticeModal } from "../components/learning/PracticeModal"
import { WrongWordsVocabularyList } from "../components/learning/WrongWordsVocabularyList"
import AsyncStorage from "@react-native-async-storage/async-storage"
import { GestureHandlerRootView } from "react-native-gesture-handler"

// 模拟的错词数据
const WRONG_WORDS_DATA = [
    {
        id: "1",
        word: "formulation",
        phonetic: "/fɔːmjuˈleɪʃ(ə)n/",
        type: "n",
        meaning: "公式化；阐述方式；规划；配方",
        syllables: ["for", "mu", "la", "tion"],
        status: "new", // new, learning, mastered
        favorite: false,
    },
    {
        id: "2",
        word: "favoritism",
        phonetic: "/ˈfeɪvərɪtɪzəm/",
        type: "n",
        meaning: "偏爱；偏袒；徇私",
        syllables: ["fa", "vor", "i", "tism"],
        status: "learning",
        favorite: true,
    },
    {
        id: "3",
        word: "turbine",
        phonetic: "/ˈtɜːbaɪn/",
        type: "n",
        meaning: "涡轮",
        syllables: ["tur", "bine"],
        status: "new",
        favorite: false,
    },
    {
        id: "4",
        word: "eject",
        phonetic: "/ɪˈdʒekt/",
        type: "v",
        meaning: "喷射；喷出；驱逐；逐出",
        syllables: ["e", "ject"],
        status: "mastered",
        favorite: false,
    },
    {
        id: "5",
        word: "ethics",
        phonetic: "/ˈeθɪks/",
        type: "n",
        meaning: "道德规范；伦理",
        syllables: ["eth", "ics"],
        status: "learning",
        favorite: false,
    },
    {
        id: "6",
        word: "exemplify",
        phonetic: "/ɪɡˈzemplɪfaɪ/",
        type: "v",
        meaning: "举例说明；例证；例示",
        syllables: ["ex", "em", "pli", "fy"],
        status: "new",
        favorite: true,
    },
]

const TABS = [
    { id: "none", label: "无遮盖" },
    { id: "translation", label: "遮盖翻译" },
    { id: "words", label: "遮盖单词" },
]

const SORT_OPTIONS = [
    { id: "normal", label: "正序" },
    { id: "random", label: "乱序" },
    { id: "alphaAsc", label: "字母正序" },
    { id: "alphaDesc", label: "字母倒序" },
]

export default function WrongWordsScreen() {
    const router = useRouter()
    const [activeTab, setActiveTab] = useState("none")
    const [activeSort, setActiveSort] = useState("normal")
    const [sortMenuVisible, setSortMenuVisible] = useState(false)
    const [settingsMenuVisible, setSettingsMenuVisible] = useState(false)
    const [selectedWordId, setSelectedWordId] = useState<string | null>(null)
    const [vocabularyData, setVocabularyData] = useState(WRONG_WORDS_DATA)
    // 测试空状态，可以设置为空数组
    // const [vocabularyData, setVocabularyData] = useState([])
    const [practiceModalVisible, setPracticeModalVisible] = useState(false)

    // 删除模式相关状态
    const [deleteMode, setDeleteMode] = useState(false)
    const [selectedWords, setSelectedWords] = useState<string[]>([])
    const [fabMenuVisible, setFabMenuVisible] = useState(false)

    // 悬浮按钮动画
    const fabAnimation = useRef(new Animated.Value(0)).current
    const fabMenuAnimation = useRef(new Animated.Value(0)).current

    // 设置状态
    const [settings, setSettings] = useState({
        split: false,
        fontSize: "medium" as "small" | "medium" | "large",
    })

    // 从本地存储加载设置
    useEffect(() => {
        const loadSettings = async () => {
            try {
                const storedFontSize = await AsyncStorage.getItem("wrongWordsFontSize")
                const storedSplit = await AsyncStorage.getItem("wrongWordsSplit")

                if (storedFontSize) {
                    setSettings((prev) => ({
                        ...prev,
                        fontSize: storedFontSize as "small" | "medium" | "large",
                    }))
                }

                if (storedSplit) {
                    setSettings((prev) => ({
                        ...prev,
                        split: storedSplit === "true",
                    }))
                }
            } catch (error) {
                console.error("加载设置失败:", error)
            }
        }

        loadSettings()
    }, [])

    const handleBack = () => {
        router.back()
    }

    const getSortLabel = () => {
        const option = SORT_OPTIONS.find((opt) => opt.id === activeSort)
        return option ? option.label : "排序"
    }

    // 更新设置并保存到本地存储
    const handleSettingsChange = async (newSettings: { split?: boolean; fontSize?: "small" | "medium" | "large" }) => {
        const updatedSettings = { ...settings, ...newSettings }
        setSettings(updatedSettings)

        try {
            // 保存到本地存储
            if (newSettings.fontSize) {
                await AsyncStorage.setItem("wrongWordsFontSize", newSettings.fontSize)
            }

            if (newSettings.split !== undefined) {
                await AsyncStorage.setItem("wrongWordsSplit", newSettings.split.toString())
            }
        } catch (error) {
            console.error("保存设置失败:", error)
        }
    }

    // 处理单词点击
    const handleWordPress = (wordId: string) => {
        if (deleteMode) {
            // 在删除模式下，点击单词会选中/取消选中它
            setSelectedWords((prev) => {
                if (prev.includes(wordId)) {
                    return prev.filter((id) => id !== wordId)
                } else {
                    return [...prev, wordId]
                }
            })
        } else {
            setSelectedWordId(wordId)
        }
    }

    // 更新单词状态
    const updateWordStatus = (wordId: string, status: "new" | "learning" | "mastered") => {
        setVocabularyData((prevData) => prevData.map((item) => (item.id === wordId ? { ...item, status } : item)))
    }

    // 切换收藏状态
    const toggleFavorite = (wordId: string) => {
        setVocabularyData((prevData) =>
            prevData.map((item) => (item.id === wordId ? { ...item, favorite: !item.favorite } : item)),
        )
    }

    const handlePracticeSelect = (practiceType: string) => {
        console.log("Selected practice:", practiceType)
        // 这里可以根据选择的练习类型进行相应的导航或其他操作
    }

    const handleUnitStudyPress = () => {
        router.push("/unit-learning-screen")
    }

    // 切换悬浮按钮菜单
    const toggleFabMenu = () => {
        if (fabMenuVisible) {
            // 关闭菜单
            Animated.parallel([
                Animated.timing(fabMenuAnimation, {
                    toValue: 0,
                    duration: 200,
                    useNativeDriver: true,
                }),
                Animated.timing(fabAnimation, {
                    toValue: 0,
                    duration: 200,
                    useNativeDriver: true,
                }),
            ]).start(() => setFabMenuVisible(false))
        } else {
            // 打开菜单
            setFabMenuVisible(true)
            Animated.parallel([
                Animated.timing(fabMenuAnimation, {
                    toValue: 1,
                    duration: 200,
                    useNativeDriver: true,
                }),
                Animated.timing(fabAnimation, {
                    toValue: 1,
                    duration: 200,
                    useNativeDriver: true,
                }),
            ]).start()
        }
    }

    // 进入删除模式
    const enterDeleteMode = () => {
        setDeleteMode(true)
        setSelectedWords([])
        toggleFabMenu()
    }

    // 退出删除模式
    const exitDeleteMode = () => {
        setDeleteMode(false)
        setSelectedWords([])
    }

    // 删除选中的单词
    const deleteSelectedWords = () => {
        if (selectedWords.length === 0) {
            Alert.alert("提示", "请先选择要删除的单词")
            return
        }

        Alert.alert("删除单词", `确定要删除选中的 ${selectedWords.length} 个单词吗？`, [
            {
                text: "取消",
                style: "cancel",
            },
            {
                text: "删除",
                style: "destructive",
                onPress: () => {
                    setVocabularyData((prev) => prev.filter((word) => !selectedWords.includes(word.id)))
                    Alert.alert("删除成功", `已删除 ${selectedWords.length} 个单词`)
                    exitDeleteMode()
                },
            },
        ])
    }

    // 悬浮按钮旋转动画
    const fabRotate = fabAnimation.interpolate({
        inputRange: [0, 1],
        outputRange: ["0deg", "45deg"],
    })

    // 悬浮菜单项动画
    const fabMenuOpacity = fabMenuAnimation
    const fabMenuTranslateY = fabMenuAnimation.interpolate({
        inputRange: [0, 1],
        outputRange: [20, 0],
    })

    return (
        <GestureHandlerRootView style={{ flex: 1 }}>
            <SafeAreaView style={styles.container} edges={["top"]}>
                <LinearGradient
                    colors={theme.colors.neutral.backgroundGradient}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 0, y: 1 }}
                    style={styles.gradientBackground}
                >
                    {/* 头部 */}
                    <View style={styles.header}>
                        <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                            <ArrowLeft size={24} color={theme.colors.neutral.black} />
                        </TouchableOpacity>

                        {/* 学习模式选项卡 */}
                        <View style={styles.headerTabs}>
                            {TABS.map((tab) => (
                                <TouchableOpacity
                                    key={tab.id}
                                    style={[styles.headerTab, activeTab === tab.id && styles.headerTabActive]}
                                    onPress={() => setActiveTab(tab.id)}
                                >
                                    <Text style={[styles.headerTabText, activeTab === tab.id && styles.headerTabTextActive]}>
                                        {tab.label}
                                    </Text>
                                </TouchableOpacity>
                            ))}
                        </View>

                        <TouchableOpacity style={styles.settingsButton} onPress={() => setSettingsMenuVisible(true)}>
                            <Settings size={24} color={theme.colors.neutral.black} />
                        </TouchableOpacity>
                    </View>

                    {/* 删除模式提示条 */}
                    {deleteMode && (
                        <View style={styles.deleteModeBanner}>
                            <Text style={styles.deleteModeText}>已选择 {selectedWords.length} 个单词</Text>
                            <View style={styles.deleteModeActions}>
                                <TouchableOpacity
                                    style={styles.deleteModeButton}
                                    onPress={deleteSelectedWords}
                                    disabled={selectedWords.length === 0}
                                >
                                    <Text
                                        style={[
                                            styles.deleteModeButtonText,
                                            selectedWords.length === 0 && styles.deleteModeButtonTextDisabled,
                                        ]}
                                    >
                                        删除
                                    </Text>
                                </TouchableOpacity>
                                <TouchableOpacity style={styles.deleteModeCloseButton} onPress={exitDeleteMode}>
                                    <X size={20} color={theme.colors.neutral.white} />
                                </TouchableOpacity>
                            </View>
                        </View>
                    )}

                    {/* 标题和排序 */}
                    <View style={styles.titleContainer}>
                        <Text style={styles.title}>错词本</Text>
                        {vocabularyData.length > 0 && (
                            <TouchableOpacity style={styles.sortButton} onPress={() => setSortMenuVisible(true)}>
                                <ArrowDownUp size={16} color={theme.colors.primary.default} style={{ marginRight: 4 }} />
                                <Text style={styles.sortButtonText}>{getSortLabel()}</Text>
                            </TouchableOpacity>
                        )}
                    </View>

                    {/* 使用WrongWordsVocabularyList组件 */}
                    <WrongWordsVocabularyList
                        vocabularyData={vocabularyData}
                        activeTab={activeTab}
                        settings={settings}
                        selectedWordId={selectedWordId}
                        onWordPress={handleWordPress}
                        onUpdateStatus={updateWordStatus}
                        onToggleFavorite={toggleFavorite}
                        deleteMode={deleteMode}
                        selectedWords={selectedWords}
                    />

                    {/* 底部按钮 */}
                    <View style={styles.bottomButtons}>
                        <TouchableOpacity style={styles.practiceButton} onPress={() => setPracticeModalVisible(true)}>
                            <BookOpen size={20} color={theme.colors.primary.default} />
                            <Text style={styles.practiceButtonText}>专项练习</Text>
                        </TouchableOpacity>

                        <TouchableOpacity style={styles.unitStudyButton} onPress={handleUnitStudyPress}>
                            <LinearGradient
                                colors={["#5B8EF4", "#4B7FE5"]}
                                start={{ x: 0, y: 0 }}
                                end={{ x: 1, y: 0 }}
                                style={styles.gradientButton}
                            >
                                <Text style={styles.unitStudyButtonText}>单元学习</Text>
                            </LinearGradient>
                        </TouchableOpacity>

                        <TouchableOpacity style={styles.integratedButton}>
                            <LinearGradient
                                colors={["#6B9BFF", "#5B8EF4"]}
                                start={{ x: 0, y: 0 }}
                                end={{ x: 1, y: 0 }}
                                style={styles.gradientButton}
                            >
                                <Text style={styles.integratedButtonText}>学练一体</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    </View>
                </LinearGradient>
                {/* 排序菜单组件 */}
                <SortMenu
                    visible={sortMenuVisible}
                    activeSort={activeSort}
                    options={SORT_OPTIONS}
                    onSelect={setActiveSort}
                    onClose={() => setSortMenuVisible(false)}
                    style={{ zIndex: 1001 }}
                />

                {/* 设置菜单组件 */}
                <SettingsMenu
                    visible={settingsMenuVisible}
                    settings={settings}
                    onSettingsChange={handleSettingsChange}
                    onClose={() => setSettingsMenuVisible(false)}
                    style={{ zIndex: 1001 }}
                />

                {/* 练习模式组件 */}
                <PracticeModal
                    visible={practiceModalVisible}
                    onClose={() => setPracticeModalVisible(false)}
                    onSelectPractice={handlePracticeSelect}
                />

                {/* 悬浮按钮菜单背景 */}
                {fabMenuVisible && (
                    <Animated.View style={[styles.fabMenuOverlay, { opacity: fabMenuOpacity }]} pointerEvents="auto">
                        <TouchableOpacity style={{ flex: 1 }} onPress={toggleFabMenu} activeOpacity={1} />
                    </Animated.View>
                )}

                {/* 悬浮按钮菜单项 */}
                {fabMenuVisible && (
                    <Animated.View
                        style={[
                            styles.fabMenu,
                            {
                                opacity: fabMenuOpacity,
                                transform: [{ translateY: fabMenuTranslateY }],
                            },
                        ]}
                    >
                        <TouchableOpacity style={styles.fabMenuItem} onPress={enterDeleteMode}>
                            <View style={[styles.fabMenuItemIcon, { backgroundColor: theme.colors.secondary.red.light }]}>
                                <Trash2 size={20} color={theme.colors.secondary.red.default} />
                            </View>
                            <Text style={styles.fabMenuItemText}>删除单词</Text>
                        </TouchableOpacity>
                    </Animated.View>
                )}

                {/* 悬浮按钮 */}
                {
                    vocabularyData.length != 0 && <TouchableOpacity style={styles.fab} onPress={toggleFabMenu} activeOpacity={0.8}>
                        <LinearGradient colors={theme.colors.primary.gradient} style={styles.fabGradient}>
                            <Animated.View style={{ transform: [{ rotate: fabRotate }] }}>
                                <Plus size={24} color={theme.colors.neutral.white} />
                            </Animated.View>
                        </LinearGradient>
                    </TouchableOpacity>
                }

            </SafeAreaView>
        </GestureHandlerRootView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    backButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    headerTabs: {
        flexDirection: "row",
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.xs,
    },
    headerTab: {
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.sm,
        borderRadius: theme.borderRadius.medium,
    },
    headerTabActive: {
        backgroundColor: theme.colors.neutral.white,
    },
    headerTabText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
    },
    headerTabTextActive: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    settingsButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    titleContainer: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    title: {
        fontSize: theme.fontSize.xl,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
    },
    sortButton: {
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.sm,
        borderRadius: theme.borderRadius.medium,
        flexDirection: "row",
        alignItems: "center",
    },
    sortButtonText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.medium,
    },
    bottomButtons: {
        flexDirection: "row",
        paddingHorizontal: theme.spacing.lg,
        paddingTop: theme.spacing.md,
        paddingBottom: Platform.OS === "ios" ? 34 : theme.spacing.lg,
        gap: theme.spacing.md,
        backgroundColor: theme.colors.neutral.white,
        borderTopWidth: 1,
        borderTopColor: theme.colors.neutral.lightGray,
    },
    practiceButton: {
        flex: 1,
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: `${theme.colors.primary.default}15`,
        paddingVertical: theme.spacing.md,
        borderRadius: theme.borderRadius.large,
        gap: theme.spacing.xs,
        height: 60,
    },
    practiceButtonText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    unitStudyButton: {
        flex: 2,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        height: 60,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.dark,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    integratedButton: {
        flex: 2,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        height: 60,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.light,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    gradientButton: {
        paddingVertical: theme.spacing.md,
        alignItems: "center",
        justifyContent: "center",
        height: "100%",
    },
    unitStudyButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
    integratedButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
    deleteModeBanner: {
        backgroundColor: theme.colors.secondary.red.default,
        paddingVertical: theme.spacing.sm,
        paddingHorizontal: theme.spacing.lg,
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
    },
    deleteModeText: {
        color: theme.colors.neutral.white,
        fontSize: theme.fontSize.sm,
        fontWeight: theme.fontWeight.medium,
    },
    deleteModeActions: {
        flexDirection: "row",
        alignItems: "center",
    },
    deleteModeButton: {
        paddingHorizontal: theme.spacing.md,
        paddingVertical: theme.spacing.xs,
        marginRight: theme.spacing.md,
    },
    deleteModeButtonText: {
        color: theme.colors.neutral.white,
        fontSize: theme.fontSize.sm,
        fontWeight: theme.fontWeight.semiBold,
    },
    deleteModeButtonTextDisabled: {
        opacity: 0.5,
    },
    deleteModeCloseButton: {
        padding: theme.spacing.xs,
    },
    fab: {
        position: "absolute",
        bottom: Platform.OS === "ios" ? 100 : 80,
        right: theme.spacing.lg,
        width: 56,
        height: 56,
        borderRadius: 28,
        zIndex: 95,
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 8,
            },
        }),
    },
    fabGradient: {
        width: "100%",
        height: "100%",
        borderRadius: 28,
        alignItems: "center",
        justifyContent: "center",
    },
    fabMenuOverlay: {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: "rgba(0, 0, 0, 0.3)",
        zIndex: 90,
    },
    fabMenu: {
        position: "absolute",
        bottom: Platform.OS === "ios" ? 170 : 150,
        right: theme.spacing.lg,
        zIndex: 95,
    },
    fabMenuItem: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        paddingVertical: theme.spacing.sm,
        paddingHorizontal: theme.spacing.md,
        marginBottom: theme.spacing.md,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.5,
                shadowRadius: 4,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    fabMenuItemIcon: {
        width: 36,
        height: 36,
        borderRadius: 18,
        alignItems: "center",
        justifyContent: "center",
        marginRight: theme.spacing.md,
    },
    fabMenuItemText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.black,
        fontWeight: theme.fontWeight.medium,
    },
})

